<script setup>
  
   import {ref,onBeforeMount,reactive} from 'vue'
   import { 
      Edit,
      Delete,
      Plus,
    } from '@element-plus/icons-vue'
    import {ElMessageBox, ElMessage} from 'element-plus'
   import {
         articleListService,
         deleteArticleService,
         updateArticleService,
         addArticleService,
      } from '@/api/article'

   import { 
         categoryListService,
      } from '@/api/category'
   import { 
         userListService,
      } from '@/api/user'
   import { QuillEditor } from '@vueup/vue-quill'
   import '@vueup/vue-quill/dist/vue-quill.snow.css'
   import { useTokenStore } from '@/stores/token'
   const tokenStore = useTokenStore()
   // 获取分类列表
   const articleList = ref([])
   const getArticleList = async ()=>{
      // 添加分页参数:防止参数被修改，做简单检查
      let params = {
         pageNum: currentPage.value ? currentPage.value : 1,
         pageSize: pageSize.value ? pageSize.value : 4, 
         createUser:formData.userId ? formData.userId:null,
         state:formData.state ? formData.state :null,
         categoryId:formData.categoryId ? formData.categoryId :null,
         title:formData.title ? formData.title :null,
      }
      const res = await articleListService(params)
      articleList.value = res.data.list
      totalPages.value = res.data.pages
      totalCount.value = res.data.total 
   }
   onBeforeMount(async ()=>{
     getArticleList()
     //初始化搜索框：用户列表、分类列表
     let res1 = await userListService()
     userList.value = res1.data

     let res2 = await categoryListService()
     categoryList.value = res2.data
   })
   
/**
 * 分页功能
 * currentPage:当前页号
 * pageSize:每页显示的记录数
 * totalPages:总页数
 * totalCount:总记录数
 * handleSizeChange:当改变每页显示的记录数时触发
 * handleCurrentChange:当改变页号时触发
 */ 

const currentPage = ref(1)
const pageSize = ref(5)
const totalPages = ref(0)
const totalCount = ref(0)
const handleSizeChange = (val) => {
   pageSize.value = val;
   //刷新数据
   getArticleList();
}

const handleCurrentChange = (val) => {
   currentPage.value = val;
   //刷新数据
   getArticleList();
}

   //删除模块
   const deleteArticle = (row) => {
   //提示用户  确认框
   ElMessageBox.confirm(
      '你确认要删除该文章吗?',
      '温馨提示',
      {
         confirmButtonText: '确认',
         cancelButtonText: '取消',
         type: 'warning',
      }
   )
      .then(async () => {
         //调用接口
         let result = await deleteArticleService(row.id);
         ElMessage({
               type: 'success',
               message: '删除成功',
         })
         //刷新列表
         getArticleList();
      })
      .catch(() => {
         ElMessage({
               type: 'info',
               message: '用户取消了删除',
         })
      })
   }


   /**
    * 添加、更新文章版块
    */
   const title = ref('')
   const dialogVisible = ref(false)
   const articleModel = reactive({
      id: null,
      title: '',
      content: '',
      categoryId: null,
      coverImg: '',
      state: '',
   })
   // 重置表单数据
   const resetArticleForm = () => {
      articleModel.id= null
      articleModel.title = ''
      // 初始化内容，并清空富文本中的内容
      articleModel.content = '<p></p>'
      articleModel.categoryId = null
      articleModel.coverImg = ''
      articleModel.state = ''
      console.log('重置表单数据::',articleModel)
   }
   const showAddDialog = ()=>{ 
      
      resetArticleForm()

      title.value = '添加文章'
      dialogVisible.value = true
   }

   const showUpdateDialog = (data) => { 
      console.log('修改文章::',data)
      dialogVisible.value = true; 
      title.value = '修改文章'
      //数据拷贝
      Object.assign(articleModel, data)
   }

   const addOrUpdateArticle = async () => { 

      if (title.value === '修改文章') {
         console.log('修改文章::::',articleModel)
         // 修改
         let result = await updateArticleService(articleModel)
         ElMessage({
            type: 'success',
            message: '修改成功',
         })
      } else {
         // 添加
         let result = await addArticleService(articleModel)
         ElMessage({
            type: 'success',
            message: '添加成功',
         })
      }
      // 关闭弹窗
      dialogVisible.value = false
      // 刷新列表
      getArticleList()
   }


   //上传成功后，对存储路径初始化
   const handleAvatarSuccess = (response) => {
      articleModel.coverImg = response.data
   }

   /**
    *  查询之前处理请求参数
    * */
   const formData = reactive({
      userId: null,
      state: '',
      categoryId: null,
      title: '',   
   })
   // 用户列表
   const userList = ref([])
   // 分类列表
   const categoryList = ref([])
   const stateList = ref([
      { stateName: '草稿' },
      { stateName: '已发布' },
   ])
  
   // 重置查询表单
   const resetSearchForm = () => {
      // 重置表单数据
      formData.userId = null
      formData.state = ''
      formData.categoryId = null
      formData.title = ''
      // 重置页码为第一页
      currentPage.value = 1
      
      // 重新加载数据
      getArticleList()
   }

</script>
<template>
   <el-card class="page-container" :body-style="{ margin: '0px auto' }">
      <template #header>
         <div class="header">
               <span>文章管理</span>
               <div class="extra">
                  <el-button type="primary" @click="showAddDialog">添加文章</el-button>
               </div>
         </div>
      </template>
      <!--查询组件  -->
   <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="标题">
         <el-input v-model="formData.title" placeholder="标题" />
      </el-form-item>
      <el-form-item label="创建人" prop="region">
         <el-select v-model.number="formData.userId" placeholder="创建人">
            <el-option v-for="user in userList" :label="user.username" :value="user.id" />
         </el-select>
      </el-form-item>
      <el-form-item label="文章分类" prop="region">
         <el-select v-model.number="formData.categoryId" placeholder="文章分类">
         <el-option v-for="category in categoryList" :label="category.categoryName" :value="category.id" />
         </el-select>
      </el-form-item>
         <el-form-item label="文章状态" prop="region">
         <el-select v-model="formData.state" placeholder="文章状态">
         <el-option v-for="state in stateList" :label="state.stateName" :value="state.stateName" />
         </el-select>
      </el-form-item>
      <el-form-item>
         <el-button type="primary" @click="getArticleList">查询</el-button>
         <el-button @click="resetSearchForm">重置</el-button>
      </el-form-item>
   </el-form>
      <el-table :data="articleList" border 
         style="width: 100%" 
         :header-cell-style="{textAlign: 'center'}"
         :cell-style="{ textAlign: 'center' }"
         height="390px"
         table-layout="fixed"
         >
         <el-table-column type="index"  label="序号"  width="60"/>
         <el-table-column prop="title" label="文章标题" />
         <el-table-column prop="state" label="状态" width="100"/>
         <el-table-column prop="category.categoryName" label="分类" width="100"/>
         <el-table-column prop="user.username" label="创建人" width="110"/>
         <el-table-column prop="createTime" label="创建时间" />
         <el-table-column prop="updateTime" label="更新时间"/>
         <el-table-column label="操作" width="150" fixed="right">
            <template v-slot="scope">
               <el-button type="primary" :icon="Edit" circle @click="showUpdateDialog(scope.row)" size="small"/>
               <el-button type="danger" :icon="Delete" circle @click="deleteArticle(scope.row)" size="small"/>
            </template>
         </el-table-column>
      </el-table>
      <el-pagination
         v-model:currentPage="currentPage"
         v-model:page-size="pageSize"
         :page-sizes="[5, 10, 15, 20]"
         layout="total, sizes, prev, pager, next, jumper"
         :hide-on-single-page="true"
         :total="totalCount"
         :page-count="totalPages"
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
      />
      <!-- 文章编辑窗口 -->
      <el-drawer
         v-model="dialogVisible"
         :title="title"
         direction="rtl"
         size="40%"
         >
      <!-- 文章表单 -->
      <el-form
         
         :rules="{}"
         label-width="120px"
         class="demo-ruleForm"
         size="default"
      >
      <el-form-item label="文章标题" prop="name">
         <el-input v-model="articleModel.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="region">
         <el-select v-model.number="articleModel.categoryId" placeholder="文章分类">
         <el-option v-for="category in categoryList" :label="category.categoryName" :value="category.id" />
         </el-select>
      </el-form-item>
      <el-form-item label="文章状态" prop="region">
         <el-select v-model="articleModel.state" placeholder="文章状态">
         <el-option v-for="state in stateList" :label="state.stateName" :value="state.stateName" />
         </el-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="region">
         <el-upload
            class="avatar-uploader"
            action="/api/upload"
            name="file"
            :auto-upload="true"
            :headers="{'Authorization':tokenStore.token}"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
         >
            <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
         </el-upload>
         </el-form-item>
         <el-form-item label="文章内容">
            <div class="editor">
                  <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html">
                  </quill-editor>
            </div>
         </el-form-item>
         <el-form-item>
         <el-button type="primary" @click="addOrUpdateArticle">提交</el-button>
         <el-button @click="resetArticleForm">重置</el-button>
      </el-form-item>
   </el-form>  


      </el-drawer>
   </el-card>
   
</template>
<style lang="scss" scoped>
 
   .page-container {
      min-height: 100%;
      box-sizing: border-box;

      .header {
         display: flex;
         align-items: center;
         justify-content: space-between;
      }
      //分页样式
      .el-pagination{
         margin-top: 10px;
         //左对齐
         justify-content: end;
      }
   }
   // 下拉框样式存在问题，修改宽度
   .el-select{
      width: 110px;
   }

   .avatar-uploader {
      :deep() {
         .avatar {
            width: 178px;
            height: 178px;
            display: block;
         }

         .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
         }

         .el-upload:hover {
            border-color: var(--el-color-primary);
         }

         .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
         }
      }
   }

   .editor {
      width: 100%;

      :deep(.ql-editor) {
         min-height: 200px;
      }
   }
</style>